<template>
	
	<el-upload
	:class='{"avatar-uploader" : type == "image"}'
	:action='action'
	:show-file-list='false'
	:name='name'
	:headers='headers'
	:on-success='handleAvatarSuccess'>
	<template v-if='type == "image"'>
		<img v-if='imageUrl' :src='imageUrl' class='avatar'>
		<i v-else class='el-icon-plus absolute xy'></i>
	</template>
	<template v-else>
		<el-button size='size' type='text'>{{fileName === '' ? '点击上传文件' : fileName}}</el-button>
	</template>
	</el-upload>

</template>

<script>
	import { baseUrl } from '@/config'
	import { getLoginToken } from '@/utils'
	export default {
		props : {
			type : {
				type : String,
				default : 'image'
			},
			fileUrl : {
				type : String,
				default : ''
			},
			
			name : {
				type : String,
				default : 'file'
			},
			
			url : {
				type : String,
				default : 'fileUpload/imageUpload'
			}
		},
		
		data() {
			return {
				action : '',
				headers : {
					Authorization : ''
				},
				fileName : '',
				imageUrl : ''
			}
		},
		
		methods : {
			handleAvatarSuccess : function(res, file){
				if(res.code == 0){
					if(this.type === 'image'){
						let reader = new FileReader()
						reader.onload = (event) => {
							this.imageUrl = event.target.result
						}
						reader.readAsDataURL(file.raw)
					}else{
						this.fileName = file.name
					}
					
					
					this.$emit('upload', res.data)
				}
			},
			
			reset : function(){
				this.fileName = ''
				this.imageUrl = ''
			}
		},
		
		watch : {
			fileUrl : function(v){
				console.log(v)
				this.imageUrl = v
			}
		},
		
		created () {
			this.headers.Authorization = getLoginToken()
			this.action = baseUrl + '/' + this.url
			
			this.imageUrl = this.fileUrl
		}
	}
</script>

<style lang='less' scoped>
	.avatar-uploader{
		height:120px;
		width:120px;
		border:1px dashed #d9d9d9;
		position:relative;
	}
	.avatar-uploader-icon{
		position:absolute;
	}
</style>
